package com.yanwq.sayhi.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.yanwq.sayhi.R;

/**
 * @author yanweiqiang.
 * @since 2015/10/29 0029.
 */
public class RatioImageView extends ImageView {
    private float widthRatio;
    private float heightRatio;

    public RatioImageView(Context context) {
        super(context);
    }

    public RatioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Ratio);
        widthRatio = typedArray.getFloat(R.styleable.Ratio_widthRatio, 640f);
        heightRatio = typedArray.getFloat(R.styleable.Ratio_heightRatio, 480f);
        typedArray.recycle();
    }

    public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (MeasureSpec.getSize(widthMeasureSpec) / (widthRatio / heightRatio)), MeasureSpec.getMode(widthMeasureSpec));
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
